#!/bin/bash

# 多实例管理脚本

show_help() {
    echo "游戏自动化多实例管理脚本"
    echo ""
    echo "用法: $0 <命令> [选项]"
    echo ""
    echo "命令:"
    echo "  list                列出所有实例"
    echo "  stop <name>         停止指定实例"
    echo "  start <name>        启动指定实例"
    echo "  restart <name>      重启指定实例"
    echo "  logs <name>         查看指定实例日志"
    echo "  exec <name>         进入指定实例容器"
    echo "  cleanup             清理所有停止的实例"
    echo "  stop-all            停止所有实例"
    echo "  port-check          检查端口占用情况"
    echo ""
    echo "示例:"
    echo "  $0 list             # 列出所有实例"
    echo "  $0 stop game1       # 停止game1实例"
    echo "  $0 logs game2       # 查看game2实例日志"
    echo "  $0 exec game1       # 进入game1容器"
}

list_instances() {
    echo "🔍 查找游戏自动化实例..."
    echo ""
    
    # 查找运行中的容器
    running=$(docker ps --filter "name=vjoyxy-automation" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}")
    if [ ! -z "$running" ]; then
        echo "✅ 运行中的实例:"
        echo "$running"
        echo ""
    fi
    
    # 查找停止的容器
    stopped=$(docker ps -a --filter "name=vjoyxy-automation" --filter "status=exited" --format "table {{.Names}}\t{{.Status}}")
    if [ ! -z "$stopped" ]; then
        echo "❌ 已停止的实例:"
        echo "$stopped"
        echo ""
    fi
    
    # 查找配置文件
    configs=$(ls docker-compose-*.yml 2>/dev/null | grep -v "docker-compose.yml")
    if [ ! -z "$configs" ]; then
        echo "📄 可用的配置文件:"
        for config in $configs; do
            instance_name=$(echo $config | sed 's/docker-compose-//g' | sed 's/.yml//g')
            echo "   - $instance_name ($config)"
        done
    fi
}

stop_instance() {
    local name=$1
    if [ -z "$name" ]; then
        echo "❌ 请指定实例名称"
        exit 1
    fi
    
    if [ -f "docker-compose-$name.yml" ]; then
        echo "🛑 停止实例: $name"
        docker compose -f "docker-compose-$name.yml" down
    else
        echo "❌ 找不到实例配置: docker-compose-$name.yml"
        exit 1
    fi
}

start_instance() {
    local name=$1
    if [ -z "$name" ]; then
        echo "❌ 请指定实例名称"
        exit 1
    fi
    
    if [ -f "docker-compose-$name.yml" ]; then
        echo "🚀 启动实例: $name"
        docker compose -f "docker-compose-$name.yml" up -d
    else
        echo "❌ 找不到实例配置: docker-compose-$name.yml"
        echo "💡 使用 ./run-multiple.sh -n $name -p <port> 创建新实例"
        exit 1
    fi
}

restart_instance() {
    local name=$1
    if [ -z "$name" ]; then
        echo "❌ 请指定实例名称"
        exit 1
    fi
    
    stop_instance $name
    sleep 2
    start_instance $name
}

show_logs() {
    local name=$1
    if [ -z "$name" ]; then
        echo "❌ 请指定实例名称"
        exit 1
    fi
    
    if [ -f "docker-compose-$name.yml" ]; then
        echo "📋 查看实例日志: $name"
        docker compose -f "docker-compose-$name.yml" logs -f
    else
        echo "❌ 找不到实例配置: docker-compose-$name.yml"
        exit 1
    fi
}

exec_instance() {
    local name=$1
    if [ -z "$name" ]; then
        echo "❌ 请指定实例名称"
        exit 1
    fi
    
    if [ -f "docker-compose-$name.yml" ]; then
        echo "🔧 进入实例容器: $name"
        docker compose -f "docker-compose-$name.yml" exec game-automation bash
    else
        echo "❌ 找不到实例配置: docker-compose-$name.yml"
        exit 1
    fi
}

cleanup_instances() {
    echo "🧹 清理停止的实例..."
    
    # 清理停止的容器
    stopped_containers=$(docker ps -aq --filter "name=vjoyxy-automation" --filter "status=exited")
    if [ ! -z "$stopped_containers" ]; then
        echo "删除停止的容器..."
        docker rm $stopped_containers
    fi
    
    # 清理无用的网络
    docker network prune -f
    
    echo "✅ 清理完成"
}

stop_all_instances() {
    echo "🛑 停止所有实例..."
    
    running_containers=$(docker ps -q --filter "name=vjoyxy-automation")
    if [ ! -z "$running_containers" ]; then
        docker stop $running_containers
        echo "✅ 所有实例已停止"
    else
        echo "ℹ️  没有运行中的实例"
    fi
}

check_ports() {
    echo "🔍 检查端口占用情况..."
    echo ""
    
    for port in {5900..5910}; do
        if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null ; then
            process=$(lsof -Pi :$port -sTCP:LISTEN | tail -n 1)
            echo "❌ 端口 $port 被占用: $process"
        else
            echo "✅ 端口 $port 可用"
        fi
    done
}

# 主逻辑
case "$1" in
    list|ls)
        list_instances
        ;;
    stop)
        stop_instance "$2"
        ;;
    start)
        start_instance "$2"
        ;;
    restart)
        restart_instance "$2"
        ;;
    logs)
        show_logs "$2"
        ;;
    exec|sh)
        exec_instance "$2"
        ;;
    cleanup)
        cleanup_instances
        ;;
    stop-all)
        stop_all_instances
        ;;
    port-check|ports)
        check_ports
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo "❌ 未知命令: $1"
        echo ""
        show_help
        exit 1
        ;;
esac 